<template>
  <div class="container">
    <!-- header -->
    <div class="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>物业服务</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/RepairManagement' }"
          >报修管理</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/home/NewRepairRequest' }">
          新建报修
        </el-breadcrumb-item>
      </el-breadcrumb>
      <h1>新建报修</h1>
    </div>
    <!-- list -->
    <div class="add-box">
      <div class="add-title">基础信息</div>
      <!-- form -->
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        class="demo-ruleForm"
        :size="formSize"
        require-asterisk-position="right"
        status-icon
      >
        <el-form-item label="关联房屋" prop="relationHouse">
          <el-cascader
            :options="relationHouseOptions"
            v-model="ruleForm.relationHouse"
            clearable
          />
        </el-form-item>

        <el-form-item label="维修项目" prop="maintenanceItems">
          <el-cascader
            :options="maintenanceItemsOption"
            v-model="ruleForm.maintenanceItems"
            clearable
          />
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="问题描述" prop="problemDescription">
          <el-input
            v-model="ruleForm.problemDescription"
            placeholder="请输入"
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="tel">
          <el-input v-model="ruleForm.tel" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="报修住户" prop="repairHouse">
          <el-input
            @focus="windowOpen"
            v-model="ruleForm.repairHouse"
            placeholder="请选择"
            :suffix-icon="Search"
            clearable
          />
        </el-form-item>

        <el-form-item label="预约日期" prop="orderDate">
          <el-date-picker
            v-model="ruleForm.orderDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="问题附件" prop="problemAttachment">
          <el-upload
            v-model:file-list="fileList"
            action="http://123.57.203.155:8077/oss/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :limit="3"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >提交</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

  <!-- 弹窗 -->
  <el-dialog v-model="chooseHouse" title="选择住户">
    <el-form :inline="true" :model="searchData" class="demo-form-inline">
      <el-form-item label="全部类型">
        <el-select
          v-model="searchData.householdType"
          placeholder="请选择住房类型"
        >
          <el-option
            v-for="v in householdTypeOption"
            :key="v.value"
            :label="v.label"
            :value="v.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchData.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="primary" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      highlight-current-row
      ref="singleTableRef"
      :data="tableData"
      @current-change="currentRowChange"
    >
      <el-table-column width="55" type="index" label="序号" />
      <el-table-column property="name" label="姓名" />
      <el-table-column property="type" label="类型" />
      <el-table-column property="state" label="状态" />
      <el-table-column
        width="200"
        property="identificationNumber"
        label="证件号码"
      />
      <el-table-column width="120" property="phoneNumber" label="手机号码" />
      <el-table-column width="150" property="room" label="房间" />
    </el-table>
    <div class="windowFooter">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="count"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        :small="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <div>
        <el-button @click="chooseHouse = false">取消</el-button>
        <el-button type="primary" @click="setCurrent(currentRow)">
          确认
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import {
  FormInstance,
  FormRules,
  UploadProps,
  UploadUserFile,
  ElMessage,
  ElTable,
} from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
const router = useRouter();
const formSize = ref('default');
const ruleFormRef = ref<FormInstance>();
const addData = reactive({
  communityId: 0,
  detail: '',
  houseId: 0,
  orderDate: '',
  phone: '',
  problemAttachment: '',
  repairProjectId: 0,
  title: '',
});
const ruleForm = reactive({
  communityId: 0,
  houseId: 0,
  relationHouse: '',
  maintenanceItems: [],
  title: '',
  problemDescription: '',
  tel: '',
  repairHouse: '',
  orderDate: '',
  fileList: [],
});

const rules = reactive<FormRules>({
  relationHouse: [{ required: true, message: '请选择房屋', trigger: 'blur' }],
  maintenanceItems: [
    { required: true, message: '请选择维修项目', trigger: 'blur' },
  ],

  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'change',
    },
    { min: 5, max: 20, message: '标题长度5-20', trigger: 'blur' },
  ],
});
//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //表单验证成功做的事情
      addData.communityId = ruleForm.communityId;
      addData.detail = ruleForm.problemDescription;
      addData.houseId = ruleForm.houseId;
      addData.orderDate = ruleForm.orderDate;
      addData.phone = ruleForm.tel;
      addData.repairProjectId = ruleForm.maintenanceItems[1];
      addData.title = ruleForm.title;
      axios({
        url: '/repair/add',
        method: 'post',
        data: {
          repairToAdd: addData,
        },
      }).then(({ data }) => {
        if (data.code == '0') {
          ElMessage.success('添加成功');
          router.push({ path: '/home/RepairManagement' });
        } else {
          ElMessage.error('添加失败');
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//级联选择器
const relationHouseOptions = [
  {
    value: 'A座',
    label: 'A座',
    children: [
      {
        value: '3单元',
        label: '3单元',
        children: [
          {
            value: '301',
            label: '301',
          },
          {
            value: '302',
            label: '302',
          },
        ],
      },
    ],
  },
  {
    value: 'B座',
    label: 'B座',
    children: [
      {
        value: '4单元',
        label: '4单元',
        children: [
          {
            value: '401',
            label: '401',
          },
          {
            value: '402',
            label: '402',
          },
        ],
      },
    ],
  },
];
const maintenanceItemsOption = [
  {
    value: '家具',
    label: '家具',
    children: [
      {
        value: 1,
        label: '床',
      },
      {
        value: 2,
        label: '沙发',
      },
      {
        value: 3,
        label: '桌子',
      },
    ],
  },
  {
    value: '电路',
    label: '电路',
    children: [
      {
        value: 4,
        label: '进户线',
      },
      {
        value: 5,
        label: '电能表',
      },
      {
        value: 6,
        label: '插座',
      },
    ],
  },
  {
    value: '水暖',
    label: '水暖',
    children: [
      {
        value: 7,
        label: '水管',
      },
      {
        value: 8,
        label: '暖气',
      },
      {
        value: 9,
        label: '热水器',
      },
    ],
  },
  {
    value: '门锁',
    label: '门锁',
    children: [
      {
        value: 10,
        label: '大门',
      },
      {
        value: 11,
        label: '卧室门',
      },
      {
        value: 12,
        label: '卫生间门',
      },
    ],
  },
  {
    value: '电路',
    label: '电路',
    children: [
      {
        value: 13,
        label: '电视',
      },
      {
        value: 14,
        label: '冰箱',
      },
      {
        value: 15,
        label: '空调',
      },
    ],
  },
];
//文件上传
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//文件上传
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  addData.problemAttachment = response.data.url;
};
//弹窗
const householdTypeOption = [
  {
    value: '全部',
    label: '全部',
  },
  {
    value: '业主',
    label: '业主',
  },
  {
    value: '亲戚',
    label: '亲戚',
  },
  {
    value: '租户',
    label: '租户',
  },
  {
    value: '朋友',
    label: '朋友',
  },
];
//弹窗列表
interface User {
  id: number;
  communityId: number;
  name: string;
  type: string;
  state: string;
  identificationNumber: string;
  phoneNumber: string;
  room: string;
}
let total = ref(0);
let page = ref(1);
let count = ref(5);
let tableData = ref<User[]>([]);
let chooseHouse = ref(false);
let searchData = reactive({
  householdType: '',
  name: '',
});
//弹窗表格渲染
const getData = () => {
  axios({
    url: '/householdManagement/list',
    params: {
      page: page.value,
      limit: count.value,
      type: searchData.householdType == '全部' ? '' : searchData.householdType,
      name: searchData.name,
    },
  }).then(({ data }) => {
    console.log(data);
    total.value = data.data.totalCount;
    tableData.value = data.data.list;
  });
};
//开启关闭弹窗
const windowOpen = () => {
  chooseHouse.value = !chooseHouse.value;
  getData();
};
//弹窗表格搜索
const onSearch = () => {
  getData();
};
//弹窗表格重置
const onReset = () => {
  searchData.householdType = '';
  searchData.name = '';
  getData();
};
//弹窗页码
const handleSizeChange = (val: number) => {
  count.value = val;
};
const handleCurrentChange = (val: number) => {
  page.value = val;
};

//弹窗单选
const singleTableRef = ref<InstanceType<typeof ElTable>>();
const currentRow = ref();
const currentRowChange = (val: User | undefined) => {
  currentRow.value = val;
};
const setCurrent = (selRow: User) => {
  ruleForm.communityId = selRow.communityId;
  ruleForm.houseId = selRow.id;
  ruleForm.repairHouse = selRow.name;
  chooseHouse.value = false;
};
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  background: #f0f2f5;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  .header {
    width: 1136px;
    height: 97px;
    background: #fff;
    margin-top: 25px;
    border-bottom: 1px solid #f0f2f5;
    .el-breadcrumb {
      height: 37px;
      line-height: 37px;
      font-size: 14px;
      margin-left: 30px;
      :deep(.el-breadcrumb__item:nth-child(1) .el-breadcrumb__inner) {
        color: #aaadb4;
      }
      :deep(.el-breadcrumb__item:nth-child(2) .el-breadcrumb__inner) {
        color: #aaadb4;
      }
    }
    h1 {
      height: 60px;
      line-height: 60px;
      margin-left: 30px;
      font-family: 'Microsoft Tai Le Bold', 'Microsoft Tai Le', sans-serif;
      font-weight: 700;
      font-style: normal;
      font-size: 20px;
    }
  }

  .add-box {
    width: 1136px;
    background: #fff;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    .add-title {
      width: 95%;
      height: 80px;
      font-family: 'PingFangSC-Medium', 'PingFang SC Medium', 'PingFang SC';
      font-weight: 500;
      font-style: normal;
      font-size: 16px;
      line-height: 80px;
    }
    .el-form {
      width: 450px;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: flex-start;
      .el-form-item {
        display: flex;
        justify-content: space-around;
        align-items: center;
        margin-bottom: 20px;

        :deep(.el-input) {
          width: 340px;
          margin-left: 10px;
        }
        :deep(.el-textarea) {
          width: 340px;
          margin-left: 10px;
        }
        .el-button {
          margin-left: 50px;
        }
      }
    }
  }
}
// 弹窗
.el-dialog {
  .el-form {
    height: 60px;
    border-top: 1px solid #d3d4d8;
    border-bottom: 1px solid #d3d4d8;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .el-table {
    margin-top: 20px;
  }
  .windowFooter {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
  }
}
</style>
